/**
 * Copyright (c) 2019-2021,  陈俊兵 (cjb6b.com@gmail.com)
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.ktjiaoyu.advance.locktype;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CountDownLatch;

/**
 *
 * @packageName com.ktjiaoyu.advance.locktype
 * @fileName HashtableCompConcurrentHashMap.java
 * @author 陈俊兵 (cjb6b.com@gmail.com)
 * @createTime 2023/7/25 16:31
 * @lastModify 2023/7/25 16:31
 * @version 1.0.0
 */
public class HashtableCompConcurrentHashMap {

    public static void main(String[] args) {
        // 使用Hashtable实现高并发
//        Map<Object, Object> map = new Hashtable<>();
        // 使用ConcurrentHashMap实现高并发
        Map<Object, Object> map = new ConcurrentHashMap<>();
        //创建计数器（初始值为100）
        CountDownLatch countDownLatch = new CountDownLatch(100);

        for (int i = 0; i < 100; i++) {
            // 启动10个线程往Map中放东西
            new Thread(()->{
                try {
                    for (int j = 0; j < 100000; j++) {
                        map.put(j, j);
                    }
                }catch (Exception e){
                    e.printStackTrace();
                }
                finally {
                    // 完成一个，计数器减一
                    countDownLatch.countDown();
                }
            }).start();
        }
        long start = System.currentTimeMillis();
        try {
            // 等待直到计数器为0
            countDownLatch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        long end = System.currentTimeMillis();
        System.out.println("一共耗时：" + (end - start) + "ms");
    }
}
